package by.alex.dzeshko.facebooksuperclient.providers;

import org.json.JSONException;
import org.json.JSONObject;
import by.alex.dzeshko.facebooksuperclient.R;
import by.alex.dzeshko.facebooksuperclient.database.DbFriendsHelper;
import by.alex.dzeshko.facebooksuperclient.providers.contract.FbContract;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class FbFriendsProvider extends ContentProvider {

	private static final String LOG_TAG = "FbFriendsProvider";
	
	private DbFriendsHelper dbHelper;

	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		return 0;
	}

	@Override
	public String getType(Uri arg0) {		
		return FbContract.FriendsColumns.FRIENDS_CONTENT_TYPE;
}

	@Override
	public Uri insert(Uri uri, ContentValues vals) {
		String jsonData = vals.getAsString("data");
		
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(jsonData);
			long id = dbHelper.addItem(jsonObject);
			Uri itemUri = ContentUris.withAppendedId(FbContract.FriendsColumns.FRIENDS_CONTENT_URI, id);
			getContext().getContentResolver().notifyChange(itemUri, null);
			return itemUri;
		} catch (JSONException e) {
			Log.e(LOG_TAG, e.toString());
		}
		return null;
	}

	@Override
	public boolean onCreate() {
		dbHelper = new DbFriendsHelper(getContext(), null);
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,	String[] selectionArgs, String sortOrder) {
		Cursor items = dbHelper.getItems();
		items.setNotificationUri(getContext().getContentResolver(), uri);
		return items;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		
		return 0;
	}

}
